package com.dxt.springmvcdemo.exceptionHandler;

import com.dxt.springmvcdemo.exception.MyBusinessException;
import com.dxt.springmvcdemo.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * BelongProject: springMVC
 * BelongPackage: com.dxt.springmvcdemo.exceptionHandler
 * Description:
 *
 * @Author 段鑫涛
 * @Create 2025/4/14 21:10
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class MyGlobalExceptionHandler{

    @ExceptionHandler(NullPointerException.class)
    public R handleNullPointerException(NullPointerException e){
        log.error("空指针异常:{}",e.getMessage());
        return R.error(500,"空指针异常",e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e){
        log.error("未知异常:{}",e.getMessage());
        return R.error(500,"未知异常",e.getMessage());
    }

    @ExceptionHandler(MyBusinessException.class)
    public R handleMyBusinessException(MyBusinessException e){
        log.error("自定义业务异常:{}",e.getMessage());
        return R.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            objectObjectHashMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        log.error("参数校验异常:{}",e.getBindingResult().getFieldError().getDefaultMessage());
        return R.error(400,e.getBindingResult().getFieldError().getDefaultMessage());
    }
}
